<?php

class stPostcardsClassGallery {
    public function __construct($config, $option = array()) {
        require_once $this->config['pluginDir'] . 'libs/amazon_gallery/sdk.class.php';
        require_once $this->config['pluginDir'] . 'functions.php';
        $this->config = $config;
        $this->option = $option;
        $fucntionName = $config['plugin_name'] . "Functions";
        $this->functions = new $fucntionName($this->config);
        
        $this->amazonS3 = new AmazonS3();
    }

    public function loadmodel($modelName) {
        $className = $modelName . "_model";
        $fileName = $this->config ['pluginDir'] . "models/{$modelName}.php";
        require_once $fileName;
        $obj = new $className($this->config);
        return $obj;
    }

    public function syncObject() {
        $stPostcardBucket_model = $this->loadmodel("stPostcardBucket");
        $stPostcardCard_model = $this->loadmodel("stPostcardCard");

        $buckets = $this->getBuckets();
        foreach ($buckets as $value) {
            $objects = $this->getObjectList($bucketName);
            $stPostcardCard_model->saveStPostcardCardList($objects, $value);
        }
        $stPostcardBucket_model->saveStPostcardBucket($buckets);
    }

    public function createBuckets($name, $region = AmazonS3::REGION_US_W1) {
        switch ($region) {
            case 'REGION_EU_W1':
                $region = AmazonS3::REGION_EU_W1;
                break;
            case 'REGION_US_E1':
                $region = AmazonS3::REGION_US_E1;
                break;
            case 'REGION_APAC_SE1':
                $region = AmazonS3::REGION_APAC_SE1;
                break;
            case 'REGION_APAC_NE1':
                $region = AmazonS3::REGION_APAC_NE1;
                break;
            default:
                $region = AmazonS3::REGION_US_E1;
                break;
        }
//        echo $region;die;
        $create_bucket_response = $this->amazonS3->create_bucket($name, $region);
        if ($create_bucket_response->isOK()) {
            $stPostcardBucket_model = $this->loadmodel("stPostcardBucket");
            $save_data = array(
                'id' => NULL,
                'name' => $name,
                'cdate' => $cdate,
            );
            return $stPostcardBucket_model->saveStPostcarBucket($save_data);
        } else {
            return false;
        }
        return false;
    }

    public function getBuckets() {
        return $this->amazonS3->get_bucket_list();
    }

    public function getObjectList($bucketName) {
        return $this->amazonS3->get_object_list($bucketName);
    }

    public function uploadObject($data, $return = false, $backcard = false, $generatecard = false) {  
        if($generatecard){            
            $folder_bucket = !empty($this->config ['folder_client'])? $this->config['folder_client'].'/':'';
        }else{
            $folder_bucket = !empty($this->config ['folder_sample'])? $this->config['folder_sample'].'/':'';
        }
        $data['upload_file'] = stripslashes($data['upload_file']);
        if(!empty($data['id']) && !$backcard){
            $stPostcardCard_model = $this->loadmodel("stPostcardCard");
            if($this->checkUploadFile($data['id'], $data)){
                if(!$this->deleteObject($data['id'], true)){
                    return false;
                }
            }else{
                $save_data = array(
                    'id' => $data['id'],
                    'name' => $data['name'],
                    'num_faces' => $data['num_faces'],
                    'cat_id' => $data['cat_id'],
                    'photographer' => $data['photographer'],
                    'description' => $data['description'],
                    'back_card_text' => $data['back_card_text'],
                    'faces' => $data['faces'],
                    'logo_file' => $data['logo_file']
                );
                return $stPostcardCard_model->saveStPostcardCard($save_data);
            }
        }
        if ($this->amazonS3->if_bucket_exists($data['bucket_name'])) {
            $stPostcardCard_model = $this->loadmodel("stPostcardCard");
            $info = pathinfo($data['upload_file']);
            $cdate = date('Y-m-d H:i:s');
            $ext = $info['extension'];
            $id = empty($data['id'])? $stPostcardCard_model->getLastId():$data['id'];
            $bucket_id = empty($data['bucket_id'])? $stPostcardCard_model->getBucketId(str_replace('/', '', $folder_bucket)):$data['bucket_id'];
            if($backcard){
                $filenames[0] = $folder_bucket."postcard_back_" . time() . '.' . $ext;
            }else{
                $filenames[0] = $folder_bucket."postcard_" . time() . '.' . $ext;
            }
            
            // upload image to amazon s3
            $img_name = basename($data['upload_file']);
            $img_name = explode('.', $img_name);
            $img_name = $img_name[0];
            $file_large = str_replace($img_name, $img_name . '-large', $data['upload_file']);
//            echo $id. $bucket_id.$cdate;
            $this->amazonS3->batch()->create_object($data['bucket_name'], $filenames[0], array(
                'fileUpload' => $file_large,
                'acl' => AmazonS3::ACL_PUBLIC,
//                'meta' => array(
//                    'id' => $id, // x-amz-meta-word
//                    'bucket_id' => $bucket_id, // x-amz-meta-ice-ice-baby
//                    'name' => $data['name'],
////                    'description' => $data['description'],
//                    'cdate' => $cdate,
//                ),
            ));

            // upload thumbnail image to amazon s3

            $thumbnail_file = str_replace($img_name, $img_name . '-thumb', $data['upload_file']);
            
            if($backcard){
                $filenames[1] = $folder_bucket."postcard_back_thumb_" . time() . '.' . $ext;
            }else{
                $filenames[1] = $folder_bucket."postcard_thumb_" . time() . '.' . $ext;
            }
            
            
            $this->amazonS3->batch()->create_object($data['bucket_name'], $filenames[1], array(
                'fileUpload' => $thumbnail_file,
                'acl' => AmazonS3::ACL_PUBLIC,
//                'meta' => array(
//                    'id' => $id, // x-amz-meta-word
//                    'bucket_id' => $bucket_id, // x-amz-meta-ice-ice-baby
//                    'name' => $data['name'] . '-thumb',
//                    'description' => $data['description'],
//                    'cdate' => $cdate,
//                ),
            ));
            $file_upload_response = $this->amazonS3->batch()->send();
            if ($file_upload_response->areOK()) {
                $response = $this->amazonS3->get_bucket_region($data['bucket_name']);
                if($response->isOK()){
                    foreach ($filenames as $filename) {
                        if(!empty($response->body) && $response->body != AmazonS3::REGION_US_E1 ){
                            if($response->body == AmazonS3::REGION_EU_W1){
                                $response->body = 'eu-west-1';
                            }
                            $img_amazon_url[] = 'https://s3-'.$response->body.'.amazonaws.com/'.$data['bucket_name'].'/'.$filename;
                        }else{
                            $img_amazon_url[] = 'https://s3.amazonaws.com/'.$data['bucket_name'].'/'.$filename;
                        }
                    }
                }
                if(!empty($data['id'])){
                    $card_id = $data['id'];
                }else{
                    $card_id = NULL;
                }
                
                if(empty($data['smt_user_id'])){
                    $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
                    
                }else{
                    $smt_user_id = $data['smt_user_id'];
                }
                
                if(empty($data['user_id'])){
                    $user_id = 0;
                    
                }else{
                    $user_id = $data['user_id'];
                }
                
                if($backcard){
                    $save_data = array(
                        'id' => $card_id,
                        'back_card_file_name' => $filenames[0],
                        'back_thumb_url' => $img_amazon_url[1],
                        'back_url' => $img_amazon_url[0]
                    );
                    
                }else{
                    $save_data = array(
                        'id' => $card_id,
                        'smt_user_id' => $smt_user_id,
                        'user_id' => $user_id,
                        'bucket_id' => $bucket_id,
                        'template_id' => $data['template_id'],
                        'name' => $data['name'],
                        'num_faces' => $data['num_faces'],
                        'logo_file' => $data['logo_file'],
                        'file_name' => $filenames[0],
                        'thumb_url' => $img_amazon_url[1],
                        'url' => $img_amazon_url[0],
                        'description' => $data['description'],
                        'back_card_text' => $data['back_card_text'],
                        'ip_creator' => $data['ip_creator'],
                        'faces' => $data['faces'],
                        'cat_id' => $data['cat_id'],
                        'photographer' => $data['photographer'],
                        'cdate' => $cdate,
                    );
                }
                
                
//                var_dump($save_data);
                unlink($data['upload_file']);
                unlink($thumbnail_file);
                unlink($file_large);
                if($return){                    
                    if($stPostcardCard_model->saveStPostcardCard($save_data)){
                        $save_data['id'] = $id;
                        return $save_data;
                    }else{
                        return false;
                    }
                    
                }else{
                    return $stPostcardCard_model->saveStPostcardCard($save_data);
                }
                
            } else {
                unlink($data['upload_file']);
                unlink($thumbnail_file);
                unlink($file_large);
                return false;
            }
        }
    }
    
    public function uploadGallery($file,$name,$thumb_file,$thumb_name,$folder){
        $this->amazonS3->batch()->create_object($this->config['gallery_bucket'], $folder.'/'.$name, array(
                'fileUpload' => $file,
                'acl' => AmazonS3::ACL_PUBLIC,
            ));
        if($thumb_file != ''){
        $this->amazonS3->batch()->create_object($this->config['gallery_bucket'], $folder.'/'.$thumb_name, array(
                'fileUpload' => $thumb_file,
                'acl' => AmazonS3::ACL_PUBLIC,
            ));
        }
        $file_upload_response = $this->amazonS3->batch()->send();

    }

    public function getCards($where = '', $data = '') {
        $stPostcardCard_model = $this->loadmodel("stPostcardCard");
        
        $current_page = $data['currentpage'];
        $smt_user_id = $data['smt_user_id'];
        $random = $data['random'];
        $is_mobile = $data['is_mobile'];
        
        $per_page = 9;
        $args = array();

        $cur_page = $current_page ? $current_page : 1;
        $limit = $per_page;
        $start = ($cur_page - 1) * $limit;
        $args['limit'] = array($start, $limit);
        if($random){
            $args['order'] = array('RAND()', ' ');
            $args['limit'] = array();
        }else{
            if($is_mobile)
                $args['limit'] = array();
            $args['order'] = array('cdate', 'desc');
        }
        
        $args['where'] = " `smt_user_id` = $smt_user_id";
        if(!empty($where)){
            $args['where'] .= ' AND '.$where;
        }
        
        
        $objects = $stPostcardCard_model->getRecords($args);
        $args['limit'] = array();
        $total = $stPostcardCard_model->countRecords($args);
        
        $total_page = ceil($total/$per_page);
        $isend = 0;
        $isfirst = 0;
        if(empty($current_page) || $current_page == 1){
            $isfirst = 1;
        }
        if($current_page == $total_page){
            $isend = 1;
        }
        $array = array(
            'total' => $total,
            'total_page' => $total_page,
            'currentpage' => $current_page,
            'isfirst' => $isfirst,
            'isend' => $isend            
        );
        $i = 0;
        $uploadDir = wp_upload_dir();
        foreach ($objects as $key => $value) {
            $faces = explode('|*|', $value->faces);
			$logoUrl = "";
			if($value->logo_file){
				 $logoUrl = $uploadDir['baseurl'].$value->logo_file;
			}
            $array['data'][$i] = array(
                'thumb' => $value->thumb_url,
                'img' => $value->url,
                'back_img' => $value->back_url,
                'cardname' => base64_encode($value->name),
                'card_description' => base64_encode($value->description),
                'back_card_text' => base64_encode($value->back_card_text),
                'template_id' => $value->id,
                'cardid' => $value->id,
                'noofface' => $value->num_faces,
                'logo_url' => $logoUrl
            );
            foreach ($faces as $face) {
                $face_value = explode(',', $face);
                $array['data'][$i]['faces'][] = array(
                    'x' => $face_value[0],
                    'y' => $face_value[1],
                    'w' => $face_value[2],
                    'h' => $face_value[3]
                );
            }
            $i++;
        }
        
        return $array;
    }
    public function deleteGallery($file)
    {
        $response = $this->amazonS3->delete_object($this->config['gallery_bucket'], $file);
        $response = $this->amazonS3->delete_object($this->config['gallery_bucket'], substr($file,0,strlen($file)-4).'-thumb'.substr($file,-4,4));
    }
    public function deleteObject($id, $notdelete = false){
        $stPostcardCard_model = $this->loadmodel("stPostcardCard");
        $args['where'] = " `id` = $id";
        $objects = $stPostcardCard_model->getRecords($args);
        $object = $objects[0];
        
        $bucket_name = $this->config['bucket_sample'];
        $response = $this->amazonS3->delete_object($bucket_name, $object->file_name);
        $file_name_thumb = str_replace('_', '_thumb_', $object->file_name);
        $response2 = $this->amazonS3->delete_object($bucket_name, $file_name_thumb);
        if($response->isOK() && $response2->isOK()){
            if($notdelete){
                return true;
            }else{
                return $stPostcardCard_model->deleteRecords($id);
            }
            
        }else{
            return false;
        }
    }
    
    public function checkUploadFile($object_id, $data){
        $stPostcardCard_model = $this->loadmodel("stPostcardCard");

        $args = array();
        $args['where'] = " `id` = $object_id";
        $objects = $stPostcardCard_model->getRecords($args);
        $object = $objects[0];
        return $data['upload_file'] != $object->thumb_url;
    }
        
}

?>